package com.redhat.auth.log.application.impl;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.springframework.stereotype.Service;

import com.dayatang.domain.InstanceFactory;
import com.redhat.auth.log.application.LogApplication;
import com.redhat.auth.log.core.LogBizQuery;
import com.redhat.auth.log.core.domain.BizLogInfo;
import com.redhat.auth.log.exception.LogException;
import com.redhat.auth.log.parse.SpecialValue;
import com.redhat.auth.log.query.LogQueryChannel;
import com.redhat.auth.log.query.LogQueryChannelImpl;
import com.redhat.auth.log.web.LogNode;

import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

@Service(value = "LogApplication")
public class LogApplicationImpl implements LogApplication {

	private static LogQueryChannel logQueryChannel;
	
	private static LogBizQuery logBizQuery;
	
	
	public static LogQueryChannel getLogQueryChannel() {
		if (logQueryChannel == null)
			logQueryChannel = InstanceFactory
					.getInstance(LogQueryChannel.class);
		return logQueryChannel;
	}
	
	


	public static LogBizQuery getLogBizQuery() {
		if(logBizQuery==null)
			logBizQuery = InstanceFactory.getInstance(LogBizQuery.class);
		return logBizQuery;
	}




	public static void setLogBizQuery(LogBizQuery logBizQuery) {
		LogApplicationImpl.logBizQuery = logBizQuery;
	}




	@Override
	public List<String> getBizOperations(){
		return getLogBizQuery().getBizOperation();
	}


	@Override
	public List<LogNode> getBizTypes(String bizOperation){
		List<String> nodeNames = getLogBizQuery().getBizTypes(bizOperation);
		List<LogNode> logNodes = new ArrayList<LogNode>();
		for(String nodeName:nodeNames){
			logNodes.add(new LogNode(bizOperation,nodeName));
		}
		return logNodes;
	}
	
	/**
	 * 根据指定业务名，业务操作类型，查询出对应的业务记录
	 * @param bizOperation
	 * @param bizType
	 * @return
	 */
	public List<BizLogInfo> getBizLogInfo(String bizOperation,String bizType){
		return getLogBizQuery().getBizLogInfo(bizOperation, bizType);
	}
	
	/**
	 * 返回一个业务描述
	 * @param language 获取指定业务描述的语言
 	 * @param key      获取指定业务描述的KEY
	 * @param value    从数据库中获取来的存储值
	 * @return
	 */
	public String getLogDescription(String language,String bizType,String bizOperation,String value){
		String path = LogApplicationImpl.class.getResource("/").getPath()+"bizlog/"+language+"/"+bizType+"/";
		
		HashMap<String,Object> recordValueMap = initRecordValue(value);
		String result = null;
	    freemarker.template.Configuration cfg = new freemarker.template.Configuration();
	   try {
		   cfg.setDirectoryForTemplateLoading(new File(path));
		   cfg.setObjectWrapper(new DefaultObjectWrapper());
		   cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
		   Template template = cfg.getTemplate(bizOperation+".ftl");
		   StringWriter writer = new StringWriter();
		   template.process(recordValueMap, writer);
		   result = writer.toString();
	} catch (IOException e) {
		result = "未找到当前日志描述文件,请联系管理员";
		e.printStackTrace();
		return result;
	} catch (TemplateException e) {
		result = "未找到当前日志描述文件,请联系管理员";
		e.printStackTrace();
		return result;
	}
		return result;
	}
	
	private HashMap<String,Object> initRecordValue(String recordValue){
		HashMap<String,Object> recordValueMap = new HashMap<String,Object>();
		String[] values = recordValue.split(SpecialValue.VALUE_SPLIT_QUERY);
		for(String value:values){
			String[] keyValues = value.split(SpecialValue.VALUE_EQUAL_QUERY);
			if(keyValues.length>1){
				if(keyValues[1].contains(SpecialValue.VALUE_PERIOD)){
					List<String> valList = new ArrayList<String>();
					String[] vals = keyValues[1].split(SpecialValue.VALUE_PERIOD_QUERY);
					for(String val:vals){
						if(val==null || val.trim().equals(""))continue;
						valList.add(val);
					}
					if(valList.size()==1) recordValueMap.put(keyValues[0], valList.get(0));
					else recordValueMap.put(keyValues[0], valList);
				}
				else recordValueMap.put(keyValues[0], keyValues[1]);
			}
		}
		return recordValueMap;
	}
	
	/**
	 * 根据主键返回一个BizLogInfo
	 * @param logId
	 * @return
	 */
	public BizLogInfo getBizLogInfo(long logId){
		return getLogBizQuery().getBizLogInfo(logId);
	}
	
}
